package org.csu.onlineedubackend.controller;

import org.csu.onlineedubackend.dto.QuestionDTO;
import org.csu.onlineedubackend.dto.StudentAnswerDTO;
import org.csu.onlineedubackend.entity.Question;
import org.csu.onlineedubackend.entity.StudentAnswer;
import org.csu.onlineedubackend.result.CommonResponse;
import org.csu.onlineedubackend.result.ResponseCode;
import org.csu.onlineedubackend.service.QuestionService;
import org.csu.onlineedubackend.service.StudentAnswerService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/api/question")
public class QuestionController {
    @Autowired
    private QuestionService questionService;
    @Autowired
    private StudentAnswerService studentAnswerService;

    // 老师布置作业（新增题目）
    @PostMapping("/create")
    public CommonResponse<QuestionDTO> createQuestion(@RequestBody QuestionDTO questionDTO) {
        System.out.println("创建作业 - 接收到的QuestionDTO: " + questionDTO);
        System.out.println("创建作业 - resourceUrls: " + questionDTO.getResourceUrls());
        
        Question question = new Question();
        BeanUtils.copyProperties(questionDTO, question);
        
        // 手动设置resourceUrls，确保正确复制
        question.setResourceUrls(questionDTO.getResourceUrls());
        
        System.out.println("创建作业 - 复制后的Question实体: " + question);
        System.out.println("创建作业 - Question实体的resourceUrls: " + question.getResourceUrls());
        
        Question created = questionService.createQuestion(question);
        
        QuestionDTO resultDTO = new QuestionDTO();
        BeanUtils.copyProperties(created, resultDTO);
        return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getDescription(), resultDTO);
    }

    // 更新作业
    @PutMapping("/update")
    public CommonResponse<QuestionDTO> updateQuestion(@RequestBody QuestionDTO questionDTO) {
        System.out.println("接收到的QuestionDTO: " + questionDTO);
        System.out.println("resourceUrls: " + questionDTO.getResourceUrls());
        
        Question question = new Question();
        BeanUtils.copyProperties(questionDTO, question);
        
        // 手动设置resourceUrls，确保正确复制
        question.setResourceUrls(questionDTO.getResourceUrls());
        
        System.out.println("复制后的Question实体: " + question);
        System.out.println("Question实体的resourceUrls: " + question.getResourceUrls());
        
        Question updated = questionService.updateQuestion(question);
        
        System.out.println("更新后的Question: " + updated);
        System.out.println("更新后的resourceUrls: " + updated.getResourceUrls());
        
        QuestionDTO resultDTO = new QuestionDTO();
        BeanUtils.copyProperties(updated, resultDTO);
        return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getDescription(), resultDTO);
    }

    // 刪除作業
    @DeleteMapping("/{questionId}")
    public CommonResponse<String> deleteQuestion(@PathVariable Integer questionId) {
        boolean deleted = questionService.deleteQuestion(questionId);
        if (deleted) {
            return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "作業刪除成功");
        } else {
            return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "作業刪除失敗");
        }
    }

    // 根據課程查詢所有題目
    @GetMapping("/course/{courseId}")
    public CommonResponse<List<QuestionDTO>> getQuestionsByCourse(@PathVariable Integer courseId) {
        List<Question> questions = questionService.getQuestionsByCourseId(courseId);
        List<QuestionDTO> questionDTOs = questions.stream()
                .map(question -> {
                    QuestionDTO dto = new QuestionDTO();
                    BeanUtils.copyProperties(question, dto);
                    
                    // 获取并设置已答人数
                    int answerCount = studentAnswerService.countDistinctStudentsByQuestionId(question.getId());
                    dto.setAnswerCount(answerCount);
                    
                    return dto;
                })
                .collect(Collectors.toList());
        return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getDescription(), questionDTOs);
    }

    // 學生提交作答
    @PostMapping("/answer/submit")
    public CommonResponse<StudentAnswerDTO> submitAnswer(@RequestBody StudentAnswerDTO answerDTO) {
        StudentAnswer answer = new StudentAnswer();
        BeanUtils.copyProperties(answerDTO, answer);
        StudentAnswer saved = studentAnswerService.submitAnswer(answer);
        
        StudentAnswerDTO resultDTO = new StudentAnswerDTO();
        BeanUtils.copyProperties(saved, resultDTO);
        return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getDescription(), resultDTO);
    }

    // 查詢某題所有學生作答
    @GetMapping("/answer/question/{questionId}")
    public CommonResponse<List<StudentAnswerDTO>> getAnswersByQuestion(@PathVariable Integer questionId) {
        List<StudentAnswer> answers = studentAnswerService.getAnswersByQuestionId(questionId);
        List<StudentAnswerDTO> answerDTOs = answers.stream()
                .map(answer -> {
                    StudentAnswerDTO dto = new StudentAnswerDTO();
                    BeanUtils.copyProperties(answer, dto);
                    return dto;
                })
                .collect(Collectors.toList());
        return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getDescription(), answerDTOs);
    }

    // 查詢某學生所有作答
    @GetMapping("/answer/student/{studentId}")
    public CommonResponse<List<StudentAnswerDTO>> getAnswersByStudent(@PathVariable Integer studentId) {
        List<StudentAnswer> answers = studentAnswerService.getAnswersByStudentId(studentId);
        List<StudentAnswerDTO> answerDTOs = answers.stream()
                .map(answer -> {
                    StudentAnswerDTO dto = new StudentAnswerDTO();
                    BeanUtils.copyProperties(answer, dto);
                    return dto;
                })
                .collect(Collectors.toList());
        return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getDescription(), answerDTOs);
    }

    // 查詢某學生某題作答
    @GetMapping("/answer/{questionId}/{studentId}")
    public CommonResponse<StudentAnswerDTO> getAnswerByQuestionAndStudent(@PathVariable Integer questionId, @PathVariable Integer studentId) {
        StudentAnswer answer = studentAnswerService.getAnswerByQuestionAndStudent(questionId, studentId);
        StudentAnswerDTO answerDTO = new StudentAnswerDTO();
        BeanUtils.copyProperties(answer, answerDTO);
        return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getDescription(), answerDTO);
    }

    // 老師批改作答
    @PostMapping("/answer/mark")
    public CommonResponse<String> markAnswer(@RequestParam Integer answerId, @RequestParam boolean isCorrect) {
        boolean ok = studentAnswerService.markAnswer(answerId, isCorrect);
        if (ok) {
            return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "批改成功");
        } else {
            return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "批改失敗");
        }
    }
} 